package com.adou.quartz.task;

import com.adou.common.util.UtilPath;
import com.adou.quartz.action.QuartzManager;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class TaskGroupAction implements TaskGroupBase {

    private static final Logger logger = LoggerFactory.getLogger(TaskGroupAction.class);

    private static final String FILE_NAME = "/scheduler.xml";

    @Autowired
    QuartzManager quartzManager;

    public boolean addTask(Task task) {
        String file = getFilePath();
        String[] s = {task.getId()};
        delTask(s);
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new File(file));
            Element root = doc.getRootElement();

            Element element = root.addElement("task");
            element.addAttribute("id", task.getId());
            element.addElement("name").setText(task.getName());
            element.addElement("state").setText("" + task.getState());
            element.addElement("type").setText("" + task.getType());
            element.addElement("content").setText(task.getContent());
            element.addElement("cronexpresssion").setText(task.getCronexpresssion());
            element.addElement("posturl").setText(task.getPostUrl());
            element.addElement("classname").setText(task.getClassname());
            element.addElement("startTime").setText(changeStr(task.getStartTime()));
            element.addElement("endTime").setText(changeStr(task.getEndTime()));
            element.addElement("repeatCount").setText(task.getRepeatCount());
            element.addElement("repeatInterval").setText(task.getRepeatInterval());
            XMLWriter output = new XMLWriter(new FileWriter(new File(file)));
            output.write(doc);
            output.close();
            if (task.getState() == 1) {
                quartzManager.addTask(task);
            }
        } catch (Exception e) {
            logger.error(e.toString());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public List getTasks() {
        String file = getFilePath();
        List list = new ArrayList();
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new File(file));
            Element root = doc.getRootElement();
            List<Element> allChildren = root.elements();
            for (int i = 0; i < allChildren.size(); i++) {
                Task task = new Task();
                task.setId(( allChildren.get(i)).attributeValue("id"));
                task.setName(( allChildren.get(i)).elementText("name"));
                task.setState(Integer.parseInt(( allChildren.get(i)).elementText("state")));
                task.setType(Integer.parseInt(( allChildren.get(i)).elementText("type")));
                task.setContent(( allChildren.get(i)).elementText("content"));
                task.setCronexpresssion(( allChildren.get(i)).elementText("cronexpresssion"));
                task.setPostUrl(( allChildren.get(i)).elementText("posturl"));
                task.setRepeatCount(( allChildren.get(i)).elementText("repeatCount"));
                task.setRepeatInterval(( allChildren.get(i)).elementText("repeatInterval"));
                task.setStartTime(( allChildren.get(i)).elementText("startTime"));
                task.setEndTime(( allChildren.get(i)).elementText("endTime"));
                task.setClassname(( allChildren.get(i)).elementText("classname"));
                list.add(task);
            }
        } catch (Exception e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return list;
    }

    public Task getTaskById(String id) {
        Task task = new Task();
        try {
            String file = getFilePath();
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new File(file));
            Element root = doc.getRootElement();
            List<Element> allChildren = root.elements();
            for (int i = 0; i < allChildren.size(); i++) {
                if (id.equals(( allChildren.get(i)).attributeValue("id"))) {
                    task.setId(( allChildren.get(i)).attributeValue("id"));
                    task.setName(( allChildren.get(i)).elementText("name"));
                    task.setState(Integer.parseInt(( allChildren.get(i)).elementText("state")));
                    task.setType(Integer.parseInt(( allChildren.get(i)).elementText("type")));
                    task.setContent(( allChildren.get(i)).elementText("content"));
                    task.setCronexpresssion(( allChildren.get(i)).elementText("cronexpresssion"));
                    task.setPostUrl(( allChildren.get(i)).elementText("posturl"));
                    task.setRepeatCount(( allChildren.get(i)).elementText("repeatCount"));
                    task.setRepeatInterval(( allChildren.get(i)).elementText("repeatInterval"));
                    task.setStartTime(( allChildren.get(i)).elementText("startTime"));
                    task.setEndTime(( allChildren.get(i)).elementText("endTime"));
                    task.setClassname(( allChildren.get(i)).elementText("classname"));
                    break;
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
            return null;
        }
        return task;
    }

    public boolean stopTask(String id) {
        try {
            quartzManager.pauseTask(id);
        } catch (SchedulerException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        String file = getFilePath();
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new File(file));
            Element root = doc.getRootElement();
            List<Element> allChildren = root.elements();
            for (int i = 0; i < allChildren.size(); i++) {
                Element ele = allChildren.get(i);
                if (ele.attributeValue("id").equals(id)) {
                    ele.element("state").setText("0");
                    break;
                }
            }
            XMLWriter output = new XMLWriter(new FileWriter(new File(file)));
            output.write(doc);
            output.close();
        } catch (Exception e) {
            logger.error(e.toString());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean resumeTask(String id) {
        try {
            quartzManager.resumeTask(id);
        } catch (SchedulerException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        String file = getFilePath();
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new File(file));
            Element root = doc.getRootElement();
            List<Element> allChildren = root.elements();
            for (int i = 0; i < allChildren.size(); i++) {
                Element ele =  allChildren.get(i);
                if (ele.attributeValue("id").equals(id)) {
                    ele.element("state").setText("1");
                    break;
                }
            }
            XMLWriter output = new XMLWriter(new FileWriter(new File(file)));
            output.write(doc);
            output.close();
        } catch (Exception e) {
            logger.error(e.toString());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean delTask(String[] ids) {
        String file = getFilePath();
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new File(file));
            Element root = doc.getRootElement();
            List<Element> allChildren = root.elements();
            for (int i = 0; i < ids.length; i++) {
                quartzManager.deleteTask(ids[i]);
                for (int j = 0; j < allChildren.size(); j++) {
                    Element ele =  allChildren.get(j);
                    if (ele.attributeValue("id").equals(ids[i])) {
                        root.remove(ele);
                        break;
                    }
                }
            }
            XMLWriter output = new XMLWriter(new FileWriter(new File(file)));
            output.write(doc);
            output.close();
        } catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        } catch (DocumentException e) {
            logger.error(e.toString());
            e.printStackTrace();
        } catch (SchedulerException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return true;
    }

    public boolean startTask(String id) {
        String file = getFilePath();
        try {
            quartzManager.deleteTask(id);
        } catch (SchedulerException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new File(file));
            Element root = doc.getRootElement();
            List<Element> allChildren = root.elements();
            for (int i = 0; i < allChildren.size(); i++) {
                Element ele =  allChildren.get(i);
                if (ele.attributeValue("id").equals(id)) {
                    Task task = new Task();
                    task.setId(ele.attributeValue("id"));
                    task.setName(ele.elementText("name"));
                    task.setState(1);
                    task.setType(Integer.parseInt(ele.elementText("type")));
                    task.setContent(ele.elementText("content"));
                    task.setCronexpresssion(ele.elementText("cronexpresssion"));
                    task.setPostUrl(ele.elementText("posturl"));
                    task.setRepeatCount(ele.elementText("repeatCount"));
                    task.setRepeatInterval(ele.elementText("repeatInterval"));
                    task.setStartTime(ele.elementText("startTime"));
                    task.setEndTime(ele.elementText("endTime"));
                    task.setClassname(ele.elementText("classname"));
                    ele.element("state").setText("1");
                    quartzManager.addTask(task);
                    break;
                }
            }
            XMLWriter output = new XMLWriter(new FileWriter(new File(file)));
            output.write(doc);
            output.close();
        } catch (Exception e) {
            logger.error(e.toString());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public String getFilePath() {
        String path = null;

        path = UtilPath.getClassPath();
        if (path != null) {
            path = path.trim();
            while (path.endsWith("/") || path.endsWith("\\")) {
                path = path.substring(0, path.length() - 1);
            }
        }

        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
            try {
                SAXReader reader = new SAXReader();
                Document doc = reader.read(new File(path + FILE_NAME));
                Element root = doc.getRootElement();
                root.addElement("tasks");
                XMLWriter output = new XMLWriter(new FileWriter(new File(path + FILE_NAME)));
                output.write(doc);
                output.close();
            } catch (FileNotFoundException e) {
                logger.error(e.toString());
                e.printStackTrace();
            } catch (IOException e) {
                logger.error(e.toString());
                e.printStackTrace();
            } catch (DocumentException e) {
                logger.error(e.toString());
                e.printStackTrace();
            }
        }
        return path + FILE_NAME;
    }

    private String changeStr(String str) {
        if (str.equals("")) {

        } else {
            str = str.replaceAll(" ", "-");
            str = str.replaceAll(":", "-");
        }
        return str;
    }
}
